package com.hzncc.flowable_diboot.controller.sales;

import com.diboot.core.controller.BaseCrudRestController;
import com.diboot.core.util.S;
import com.diboot.core.vo.JsonResult;
import com.diboot.core.vo.Pagination;
import com.diboot.iam.annotation.BindPermission;
import com.diboot.iam.annotation.Log;
import com.diboot.iam.annotation.OperationCons;
import com.diboot.iam.service.SystemConfigService;
import com.diboot.iam.util.IamSecurityUtils;
import com.hzncc.flowable_diboot.dto.ClueDTO;
import com.hzncc.flowable_diboot.entity.Clue;
import com.hzncc.flowable_diboot.service.ClueService;
import com.hzncc.flowable_diboot.util.ConstantUtil;
import com.hzncc.flowable_diboot.vo.ClueDetailVO;
import com.hzncc.flowable_diboot.vo.ClueListVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.harmony.unpack200.bytecode.forms.IincForm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 线索 相关rest接口
 *
 * @author MyName
 * @version 1.0
 * @date 2024-06-06
 * Copyright © MyCorp
 */
@Slf4j
@RequestMapping("/clue")
@BindPermission(name = "线索")
@RestController
public class ClueController extends BaseCrudRestController<Clue> {

    @Autowired
    private ClueService clueService;
    @Autowired
    private SystemConfigService systemConfigService;

    @Value("${diboot.tenant.is}")
    private String isTenantId;

    /**
     * 查询资源对象的列表VO记录
     * <p>
     * url请求参数示例: ?fieldA=abc&pageSize=20&pageIndex=1&orderBy=id
     * </p>
     *
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_LIST)
    @BindPermission(name = OperationCons.LABEL_LIST, code = OperationCons.CODE_READ)
    @GetMapping()
    public JsonResult<List<ClueListVO>> getListVOMapping(ClueDTO queryDto, Pagination pagination, String type) throws Exception {
        return clueService.selectClue(queryDto, pagination, type);
    }

    /**
     * 根据id查询资源对象的详情VO
     *
     * @param id ID
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DETAIL)
    @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/{id}")
    public JsonResult<ClueDetailVO> getDetailVOMapping(@PathVariable("id") String id) throws Exception {
        ClueDetailVO detailVO = clueService.getViewObject(id, ClueDetailVO.class);
        return JsonResult.OK(detailVO);
    }


    /**
     * 创建资源对象数据
     *
     * @param clue
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_CREATE)
    @BindPermission(name = OperationCons.LABEL_CREATE, code = OperationCons.CODE_WRITE)
    @PostMapping()
    public JsonResult<?> createModelMapping(@RequestBody Clue clue) throws Exception {
        BigDecimal value = systemConfigService.findConfigValue(ConstantUtil.VALID, ConstantUtil.VALID_CLUE);
        clue.setExpirationTime(value.longValue());
        boolean success = clueService.createEntity(clue);
        log.debug("新建数据 线索:{} {}", clue.getId(), success ? "成功" : "失败");
        return JsonResult.OK(clue.getId());
    }

    /**
     * 批量创建资源对象数据
     *
     * @param clueList
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_BATCH_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @PostMapping("/batch")
    public JsonResult<?> batchCreateModelMapping(@RequestBody List<Clue> clueList) throws Exception {
        boolean success = clueService.createEntities(clueList);
        log.debug("批量新建数据 线索 {}", success ? "成功" : "失败");
        return JsonResult.OK(success);
    }

    /**
     * 根据id更新资源对象
     *
     * @param clue
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @PutMapping("/{id}")
    public JsonResult<?> updateModelMapping(@PathVariable("id") String id, @RequestBody Clue clue) throws Exception {
        boolean success = clueService.updateEntity(clue);
        log.debug("更新数据 线索:{} {}", id, success ? "成功" : "失败");
        return JsonResult.OK(success);
    }

    /**
     * 根据id删除资源对象
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DELETE)
    @BindPermission(name = OperationCons.LABEL_DELETE, code = OperationCons.CODE_WRITE)
    @DeleteMapping("/{id}")
    public JsonResult<?> deleteModelMapping(@PathVariable("id") String id) throws Exception {
        boolean success = clueService.deleteEntity(id);
        log.debug("删除数据 线索:{} {}", id, success ? "成功" : "失败");
        return JsonResult.OK(success);
    }

    /**
     * 根据ids集合删除资源对象
     *
     * @param ids
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_BATCH_DELETE)
    @BindPermission(name = OperationCons.LABEL_DELETE, code = OperationCons.CODE_WRITE)
    @PostMapping("/batch-delete")
    public JsonResult<?> deleteEntityMapping(@RequestBody List<String> ids) throws Exception {
        boolean success = clueService.deleteEntities(ids);
        log.debug("批量删除数据 线索:{} {}", ids, success ? "成功" : "失败");
        return JsonResult.OK(success);
    }

    /**
     * 线索转移
     *
     * @return
     * @author 陈广煜
     * @date 2024/6/6
     */
    @Log(operation = OperationCons.LABEL_BATCH_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @PostMapping("/trans")
    public JsonResult<?> trans(String uid, @RequestParam("ids") ArrayList<String> ids) {
        JsonResult<?> res = clueService.checkClue(ids.get(0));
        if (res.getCode() != 0) {
            return res;
        }
        clueService.trans(uid, ids);
        return JsonResult.OK();
    }

    /**
     * 线索分配
     *
     * @return
     * @author 陈广煜
     * @date 2024/6/6
     */
    @Log(operation = ConstantUtil.PERMISSION_DISTRIBUTE_LABEL)
    @BindPermission(name = ConstantUtil.PERMISSION_DISTRIBUTE_LABEL, code = ConstantUtil.PERMISSION_DISTRIBUTE)
    @PostMapping("/dis")
    public JsonResult<?> dis(String uid, @RequestParam("ids") List<String> ids) {
        clueService.distribute(uid, ids);
        return JsonResult.OK();
    }


    /**
     * 线索关注
     *
     * @return
     * @author 陈广煜
     * @date 2024/6/13
     */
    @Log(operation = OperationCons.LABEL_BATCH_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @GetMapping("/star")
    public JsonResult<?> star(String cid) {
        String uid = IamSecurityUtils.getCurrentUserId();
        Clue entity = clueService.getEntity(cid);
        List<String> starUids = entity.getStarUids();
        if (starUids == null) {
            entity.setStarUids(Collections.singletonList(uid));
        } else {
            starUids.add(uid);
        }
        clueService.updateEntity(entity);
        return JsonResult.OK();
    }

    /**
     * 线索取关
     *
     * @return
     * @author 陈广煜
     * @date 2024/6/13
     */
    @Log(operation = OperationCons.LABEL_BATCH_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @GetMapping("/cancel")
    public JsonResult<?> cancel(String cid) {
        String uid = IamSecurityUtils.getCurrentUserId();
        Clue entity = clueService.getViewObject(cid, ClueListVO.class);
        entity.setStarUids(entity.getStarUids().stream().filter(e -> !Objects.equals(uid, e)).collect(Collectors.toList()));
        clueService.updateEntity(entity);
        return JsonResult.OK();
    }

    /**
     * 线索池转移
     *
     * @return
     * @author 陈广煜
     * @date 2024/6/13
     */
    @Log(operation = OperationCons.LABEL_BATCH_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @GetMapping("/transPool")
    public JsonResult<?> transPool(String cid, String tid) {
        Clue clue = clueService.getEntity(cid);
        clue.setTenantId(tid);
        clueService.updateEntity(clue);
        // todo 转移记录
        return JsonResult.OK();
    }

    /**
     * 线索转化
     *
     * @return
     * @author 陈广煜
     * @date 2024/6/13
     */
    @Log(operation = OperationCons.LABEL_BATCH_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @GetMapping("/convert")
    public JsonResult<?> conversionToCustomers(String customerId, String cid) {
        Clue clue = clueService.getEntity(cid);
        if (S.equals(clue.getStatus(), "used")) {
            return JsonResult.FAIL_INVALID_PARAM("已转化,不能继续操作！");
        }
        clue.setCustomerId(customerId);
        clue.setStatus("used");
        clueService.updateEntity(clue);
        return JsonResult.OK();
    }

    /**
     * 放入线索池
     *
     * @return
     * @author 陈广煜
     * @date 2024/6/13
     */
    @Log(operation = OperationCons.LABEL_BATCH_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @PostMapping("/push")
    public JsonResult<?> pushPool(@RequestBody Clue clue) {
        Clue entity = clueService.getEntity(clue.getId());
        if (S.equals(entity.getStatus(), "used")) {
            return JsonResult.FAIL_INVALID_PARAM("已转化,不能继续操作！");
        }
        entity.setReason(clue.getReason());
        entity.setFlag(0);
        entity.setEnterDays(0L);
        clueService.updateEntity(entity);
        return JsonResult.OK();
    }

    /**
     * 网站留言
     *
     * @param clues
     * @return
     */
    @PostMapping("/website")
    public JsonResult<?> website(@RequestBody List<Clue> clues) {
        if (clues == null || clues.isEmpty()) {
            return JsonResult.FAIL_INVALID_PARAM("数据为空");
        }
        clues.forEach(clue -> {
            clue.setTenantId(isTenantId);
            clue.setSource("website");
            clue.setFlag(0);
        });
        clueService.createEntities(clues);
        return JsonResult.OK();
    }

}